<style type="text/css">
    .btnAnswer{
        background-image: none;
        background-color: red;
    }
</style>
<script language='javascript'>
    var img = '';
    var object = "";
    var formSlide;
    var containerTypeSM;
    var fObjectSM, fObjectTP ;
    var formQuestions;
    var _editor;
    var n = 0; //<-- usado para ir creando "name" de cada formulario dinamicamente
    var deletedAnswers = [];
    var grid;
    var formResource;
    var CFG;
    var formObject;
    var _question = null;
    var disableTabs = false;
    var _ObjectID = null;

    <?php if(isset($object)){?>
        _ObjectID = <?php echo $object->id;?>;
    <?php } ?>

    $(document).ready(function() {
        Ext.Loader.setConfig({enabled: true});
        Ext.Loader.setPath('Ext.ux', '../ux/');
        
        Ext.require([
            'Ext.grid.*',
            'Ext.data.*',
            'Ext.util.*',
            'Ext.toolbar.Paging',
            'Ext.ModelManager',
            'Ext.tip.QuickTipManager',
            'Ext.form.*',
            'Ext.layout.container.Column',
            'Ext.tab.*'
        ]);
        
        Ext.override(Ext.form.Panel, {
             clearForm:function(){
                Ext.each(this.getForm().getFields().items, function(field){
                    field.setValue('');
                    field.remove();
                });
             }
        });


        var id = 0;
        var win;
        var loadQuestions = false;

        if(_ObjectID){
            Ext.Ajax.request({
                url: BASE_URL+"objects/get",
                params:{id:_ObjectID},
                success: function(response, opts) {
                   var obj = Ext.decode(response.responseText);
                   object = obj.data;
                   _init(object);
                },
                failure: function(response, opts) {
                   console.log('server-side failure with status code ' + response.status);
                }
            });
        }
        else{
            _init(null)
        }

        function _init(object){

            CFG = Ext.decode('<?php echo json_encode($cfg); ?>');

            var stSlideEffects = new Ext.data.JsonStore({
                fields:
                        [
                            {name: 'name', mapping: 'name', type: 'string'},
                            {name: 'description', mapping: 'description', type: 'string'}
                        ],
                data: [
                    {name: 'up'},
                    {name: 'down'},
                    {name: 'left'},
                    {name: 'right'},
                    {name: 'fade'}
                ]
            });
            var stTypeQuestions = new Ext.data.JsonStore({
                autoLoad: true,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'typequestions/loadList',
                    method: 'GET',
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'name', mapping: 'name', type: 'string'}
                ]
            });
            var stObjectStatus = new Ext.data.JsonStore({
                autoLoad: false,
                remoteSort: false,
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'name', mapping: 'name', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'}
                ],
                data:[
                    {id: CFG.object_enabled, name: "HABILITADO" },
                    {id: CFG.object_disabled, name: "DESHABILITADO" },
                    {id: CFG.object_develop, name: "DESARROLLO" },
                    {id: CFG.object_publish, name: "PUBLICAR" }
                ]
            });
            var stCategories = new Ext.data.JsonStore({
                autoLoad: true,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'categories/loadList',
                    method: 'GET',
                    extraParams: {type_objects_id: CFG.type_object_theme},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                        [
                            {name: 'id', mapping: 'id', type: 'string'},
                            {name: 'name', mapping: 'name', type: 'string'},
                            {name: 'description', mapping: 'description', type: 'string'}
                        ]
            });
            var stCategorieResources = new Ext.data.JsonStore({
                autoLoad: true,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'categories/loadTypeResourcesList',
                    method: 'GET',
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                        [
                            {name: 'id', mapping: 'id', type: 'string'},
                            {name: 'name', mapping: 'name', type: 'string'},
                            {name: 'description', mapping: 'description', type: 'string'}
                        ]
            });
            var stSlides = new Ext.data.JsonStore({
                autoLoad: false,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'slides/loadList',
                    method: 'GET',
                //    extraParams: {elem_presentations_id: object.presentation.id},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                        [
                            {name: 'id', mapping: 'id', type: 'string'},
                            {name: 'title', mapping: 'title', type: 'string'},
                            {name: 'imgpath', mapping: 'imgpath', type: 'string'},
                            {name: 'audiopath', mapping: 'audiopath', type: 'string'},
                            {name: 'index', mapping: 'index', type: 'string'},
                            {name: 'effect', mapping: 'effect', type: 'string'},
                            {name: 'description', mapping: 'description', type: 'string'}
                        ]
            });
            //store de recursos y archivos
            var stResourceFiles = new Ext.data.JsonStore({
                autoLoad: false,
                remoteSort:true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'objects/loadResourceFiles',
                    method: 'GET',
                  //  extraParams: {parent: object.id},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'},
                    {name: 'name', mapping: 'name', type: 'string'},
                    {name: 'status', mapping: 'status', type: 'string'},
                    {name: 'parent', mapping: 'parent', type: 'string'},
                    {name: 'content', mapping: 'content', type: 'string'},
                    {name: 'category_id', mapping: 'category_id', type: 'string'},
                    {name: 'category_name', mapping: 'category_name', type: 'string'},
                    {name: 'dcreated', mapping: 'dmodified', type: 'string'},
                    {name: 'dmodified', mapping: 'dcreated', type: 'string'},
                    {name: 'ucreated', mapping: 'ucreated', type: 'string'},
                    {name: 'umodified', mapping: 'umodified', type: 'string'}
                ]
            });
            
            if(object && object.test && object.test.id)   loadQuestions = true;
            
            function generateUID(separator) {
                /// <summary>
                ///    Creates a unique id for identification purposes.
                /// </summary>
                /// <param name="separator" type="String" optional="true">
                /// The optional separator for grouping the generated segmants: default "-".    
                /// </param>

                var delim = separator || "-";

                function S4() {
                    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                }

                return (S4() + S4() + delim + S4() + delim + S4() + delim + S4() + delim + S4() + S4() + S4());
            };
            function resetFullForm(dynamicForm){
                if(dynamicForm){
                    dynamicForm.getForm().reset();
                    dynamicForm.getForm().getFields().items.forEach(function(item){
                        var ct = item.up('container');
                        dynamicForm.remove(ct,true);
                    });
                    dynamicForm.getForm().getFields().items = [];
                }
                return;
            }
            function _sendQuestion(url){
                if(object.test && object.test.id){
                    var answers = [];
                    var question = {};
                    question.elem_test_id = object.test.id;
                    question.description = CKEDITOR.instances.ckeditor.document.getBody().getHtml();
                    question.type_questions_id = formQuestions.getForm().findField("type_questions_id").getValue();
                    question.id = formQuestions.getForm().findField("id").getValue();
                    question.parent = 0;
                    //si esta visible..
                    if(Ext.getCmp('fObjectSM') && Ext.getCmp('fObjectSM').isVisible()){
                        var form =  Ext.getCmp('ctDinamico').getForm();
                        for(var i=0;i<=Ext.getCmp('ctDinamico').items.items.length;i++){
                            var answer = {};
                            if(form.findField("description_"+i)){
                                answer.description = form.findField("description_"+i).getValue();
                            }
                            if(form.findField("explication_"+i)){
                                answer.explication = form.findField("explication_"+i).getValue();
                            }
                            if(form.findField("value_"+i) && form.findField("value_"+i).getValue('on')){
                                answer.value = true;
                            }
                            if(form.findField("id_"+i)){
                                answer.id = form.findField("id_"+i).getValue();
                            }
                            if(typeof answer.description !== "undefined" && answer.description !== "")
                                answers.push(answer);
                        }
                        
                        resetFullForm(Ext.getCmp('ctDinamico'));

                    }
                    else{
                        //si es Termino pareado
                        if(Ext.getCmp('fObjectTP') && Ext.getCmp('fObjectTP').isVisible()){
                            var form =  Ext.getCmp('ctDinamicoTP').getForm();
                            for(var i=0;i<=Ext.getCmp('ctDinamicoTP').items.items.length;i++){
                                var answer = {};
                                if(form.findField("description1_"+i)){
                                    answer.description1 = form.findField("description1_"+i).getValue();
                                }
                                if(form.findField("description2_"+i)){
                                    answer.description2 = form.findField("description2_"+i).getValue();
                                }
                                
                                if(form.findField("id1_"+i)){
                                    answer.id1 = form.findField("id1_"+i).getValue();
                                }
                                if(form.findField("id2_"+i)){
                                    answer.id2 = form.findField("id2_"+i).getValue();
                                }
                                if(typeof answer.description1 !== "undefined" && answer.description1 !== "")
                                    answers.push(answer);
                            }
                            
                            resetFullForm(Ext.getCmp('ctDinamicoTP'));
                        }
                        //si es verdadero o falso
                        if(Ext.getCmp('ctVF').isVisible()){
                            var answer = {};
                            question.value =  formQuestions.getForm().findField("enunciadoValue").getValue();
                        }
                    }
                    question.answers = answers;
                    question.deletedAnswers = deletedAnswers;
                    Ext.Ajax.request({
                        url: url,
                        params:{
                            elem_test_id:question.elem_test_id,
                            type_questions_id:question.type_questions_id,
                            description:question.description,
                            question: Ext.encode(question)
                        },
                        success: function(response, opts) {
                           var obj = Ext.decode(response.responseText);
                           formQuestions.getForm().reset();
                           //Ext.getCmp('ctDinamico').getForm().getFields().items = [];
                                    
                           _editor.setData("");
                           //actualizamos preguntas en contenedor
                           stQuestions.load();
                           win.hide();
                        },
                        failure: function(response, opts) {
                           console.log('server-side failure with status code ' + response.status);
                        }
                    });
                }
                else{
                    alert("Debe definir la prueba en el formulario superior antes de crear las preguntas.");
                }
            }
            //retorna formulario de preguntas de un tipo determinado
            function _getSMAnswerFrom(k,answer,type){
                //si es SM
                var _id = generateUID();
                if(type== 3){
                    var checked = false;
                    var value = {};
                    if(answer){
                        value.id = answer.id;
                        value.description = answer.description;
                        value.explication = answer.explication;
                        checked = (answer.value === "1");
                    }
                    else{
                        value.id = "";
                        value.description = "";
                        value.explication = "";
                    }
                    
                    console.log(_id)

                    return {
                        layout: 'hbox',
                        xtype: 'container',
                        border:false,
                        frame: false,
                        items:[
                            {
                                xtype:'hidden',
                                name:'id_'+k,
                                value:value.id
                            },
                            {
                                xtype:'hidden',
                                name:'explication_'+k,
                                //id:_id,
                                value:value.explication
                            },
                            {
                                xtype: 'radiofield',
                                margin: '0 0 0 10'
                            },
                            {
                                xtype: 'textfield',
                                margin: '0 0 0 10',
                                value:value.description,
                                name:'description_'+k
                            },
                            {
                                xtype: 'checkboxfield',
                                margin: '0 0 0 10',
                                checked:checked,
                                name:'value_'+k
                            },
                            {
                                xtype: 'button',
                                margin: '0 0 0 10',
                                text:'Explicación',
                                iconCls: 'x-icon-add',
                                handler:function(btn){
                                    var winExplication = new Ext.Window({
                                        title: 'Explicación',
                                        resizable: false,
                                        width: 300,
                                        height: 200,
                                        forceFit: true,
                                        frame: false,
                                        layout: 'fit',
                                        modal: true,
                                        plain: true,
                                        buttonAlign: 'center',
                                        items: [
                                            {
                                                xtype:'textarea',
                                                margin:'10',
                                                id:_id,
                                                value:Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).getValue()
                                            }
                                        ],
                                        closable: false,
                                        buttons: [
                                            {
                                                text: 'Cerrar',
                                                iconCls: 'x-icon-cancel',
                                                handler: function() {
                                                    Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).setValue(Ext.getCmp(_id).getValue());
                                                    winExplication.hide();
                                                }
                                            }
                                        ]
                                    });

                                    winExplication.on('close', function() {
                                        Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).setValue(Ext.getCmp(_id).getValue());
                                        win.toggleCollapse();
                                    });
                                    winExplication.on('minimize', function() {
                                        Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).setValue(Ext.getCmp(_id).getValue());
                                        win.toggleCollapse();
                                    });
                                    winExplication.show();
                                }
                            },
                            {
                                xtype: 'button',
                                margin: '0 0 0 10',
                                iconCls: 'x-icon-delete',
                                handler:function(btn){
                                    var ct = btn.up('container');
                                    deletedAnswers.push(Ext.getCmp('ctDinamico').getForm().findField('id_'+k).getValue());
                                    Ext.getCmp('ctDinamico').remove(ct,true);
                                }
                            }
                        ]
                    };
                }
                else{//respuesta termino pareado
                    if(type == 2){
                        var value = {};
                        value.inner = {};

                        if(answer){
                            value.id = answer.id;
                            value.description = answer.description;
                            checked = (answer.value === "1");

                            value.inner.id = answer.answer.id;
                            value.inner.description = answer.answer.description;
                        }
                        else{
                            value.id = "";
                            value.description = "";
                            value.inner.id = "";
                            value.inner.description = "";
                        }
                    
                        return {
                            layout: 'hbox',
                            xtype: 'container',
                            border:false,
                            frame: false,
                            items:[
                                {
                                    xtype:'hidden',
                                    name:'id1_'+k,
                                    value:value.id
                                },
                                {
                                    xtype:'hidden',
                                    name:'id2_'+k,
                                    value:value.inner.id
                                },
                                {
                                    xtype: 'textfield',
                                    margin: '0 0 0 10',
                                    fieldLabel:'Termino 1',
                                    width:200,
                                    value:value.description,
                                    name:'description1_'+k
                                },
                                {
                                    xtype: 'textfield',
                                    margin: '0 0 0 10',
                                    fieldLabel:'Termino 2',
                                    width:200,
                                    value:value.inner.description,
                                    name:'description2_'+k
                                },
                                {
                                    xtype: 'button',
                                    margin: '0 0 0 10',
                                    iconCls: 'x-icon-delete',
                                    handler:function(btn){
                                        var ct = btn.up('container');
                                        deletedAnswers.push(Ext.getCmp('ctDinamicoTP').getForm().findField('id1_'+k).getValue());
                                        deletedAnswers.push(Ext.getCmp('ctDinamicoTP').getForm().findField('id2_'+k).getValue());
                                        Ext.getCmp('ctDinamicoTP').remove(ct,true);
                                    }
                                }
                            ]
                        };
                    }
                }
            }
            var stQuestions = new Ext.data.JsonStore({
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'questions/loadList',
                    method: 'GET',
                 //   extraParams: {elem_test_id: object.test.id},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'},
                    {name: 'type_objects_id', mapping: 'type_objects_id', type: 'string'},
                    {name: 'type_questions_id', mapping: 'type_questions_id', type: 'string'},
                    {name: 'answers', mapping: 'answers', type: 'object'},
                    {name: 'innerAnswers', mapping: 'innerAnswers', type: 'object'}
                ],
                listeners:{
                    load:function(store, records, options){
                        var list = "";
                        var nQ = 1;
                        jQuery.each(records,function(i,item){
                            item = item.data;
                            
                            var buttonCopiar = "<button class='btn btnCopy' id='"+item.id+"' title='Copiar' alt='Copiar'><i class='icon-file'></i></button>";
                            var buttonEliminar = "<button class='btn btnRemove' id='"+item.id+"' title='Eliminar' alt='Copiar'><i class='icon-trash'></i></button>";
                            var buttonEditar = "<button class='btn btnEdit' id='"+item.id+"' title='Editar' alt='Copiar'><i class='icon-edit'></i></button>";
                            var buttons = buttonEliminar+buttonEditar+buttonCopiar;
                            var li = "<li class='li_question'><div><span class='test_question_number'>"+(nQ++)+".- </span>"+item.description+"</div>"+buttons+"<ul>";
                            var select = "";

                            //terminos pareados
                            if(item.type_questions_id == 2){
                                //creamos un select
                                jQuery.each(item.innerAnswers,function(k,inner){
                                    select = select + "<option>"+inner.description+"</option>";
                                });
                                select = "<select style='width:120px;float:left;height:20px;'>"+select+"</select>";
                            }

                            jQuery.each(item.answers,function(i,answer){
                      //          console.log(item)
                                //seleccion multiple
                                if(item.type_questions_id == 3)
                                    li = li + "<li><input type='checkbox'/><label>"+answer.description+"</label></li>";
                                //terminos pareados
                                if(item.type_questions_id == 2){
                                    li = li + "<li><label style='width:150px;float:left;height:20px;'>"+answer.description+"</label>"+select+"</li>";
                                }
                            });
                            li = li+"</ul></li>";
                            list = list+li;
                        });
                        jQuery("#divCreatedQuestions").html(list);
                        jQuery(".btnCopy").on("click",function(){
                            var id = jQuery(this).attr("id");
                            Ext.Ajax.request({
                                url: BASE_URL+'questions/duplicate',
                                params:{
                                    id:id
                                },
                                success: function(response, opts) {
                                   var obj = Ext.decode(response.responseText);
                                   //actualizamos preguntas en contenedor
                                   stQuestions.load();
                                },
                                failure: function(response, opts) {
                                   console.log('server-side failure with status code ' + response.status);
                                }
                            });
                        });
                        jQuery(".btnRemove").on("click",function(){
                            var _this = this;
                            var id = jQuery(this).attr("id");
                            Ext.Ajax.request({
                                url: BASE_URL+'questions/del',
                                params:{
                                    id:id
                                },
                                success: function(response, opts) {
                                   var res = Ext.decode(response.responseText);
                                   if(res.success){
                                        jQuery(_this).parent().slideUp("slow",function(){
                                            stQuestions.load();
                                        });
                                   }
                                   else{
                                       Ext.MessageBox.show({
                                            title: 'Error en la operaci\u00F3n',
                                            msg: res.msg+"<br>"+_getErrorFromArray(res.errors),
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.ERROR,
                                            minWidth: 400
                                        });
                                   }
                                },
                                failure: function(response, opts) {
                                   console.log('server-side failure with status code ' + response.status);
                                }
                            });
                        });
                        jQuery(".btnEdit").on("click",function(){
                            var id = jQuery(this).attr("id");
                            Ext.Ajax.request({
                                url: BASE_URL+'questions/get',
                                params:{
                                    id:id
                                },
                                success: function(response, opts) {
                                    var res = Ext.decode(response.responseText);
                                    var question = res.data;
                                   //limpiando contenedor dinamico si o si
                                    resetFullForm(Ext.getCmp('ctDinamico'));
                                    resetFullForm(Ext.getCmp('ctDinamicoTP'));
                                    add(question);
                                },
                                failure: function(response, opts) {
                                   console.log('server-side failure with status code ' + response.status);
                                }
                            });
                        });
                    }
                }
            });
            
            

            formSlide = Ext.create('Ext.form.Panel', {
                bodyPadding: 20,
                disabled: true,
                flex: .5,
                height: 540,
                url: BASE_URL + 'slides/add',
                fieldDefaults: {
                    labelAlign: 'left'
                },
                items: [
                    {
                        xtype: 'textfield',
                        name: 'title',
                        fieldLabel: 'Título'
                    },
                    {
                        xtype: 'textarea',
                        name: 'description',
                        fieldLabel: 'Descripción'
                    },
                    {
                        xtype: 'hidden',
                        name: 'id'
                    },
                    {
                        xtype: 'hidden',
                        name: 'elem_presentations_id'
                        /*,
                        value: object.presentation.id*/
                    },
                    {
                        xtype: 'hidden',
                        name: 'imgpath'
                    }, {
                        xtype: 'hidden',
                        name: 'audiopath'
                    }
                    ,
                    {
                        xtype: 'textfield',
                        name: 'index',
                        fieldLabel: 'Orden'
                    }, {
                        xtype: 'combo',
                        store: stSlideEffects,
                        editable: false,
                        displayField: 'name',
                        name: 'effect',
                        valueField: 'name',
                        fieldLabel: 'Efecto Transición',
                        listeners: {
                            change: function(a, b, c) {
                                if (b != "fade") {
                                    $("#imgslide").show("slide", {direction: b}, 1000);
                                }
                                else {
                                    jQuery("#imgslide").fadeOut('slow', function() {
                                        jQuery("#imgslide").fadeIn();
                                    });
                                }
                            }
                        },
                        queryMode: 'local'
                    }
                ],
                buttons: [
                    {
                        xtype: 'button',
                        margin: '20',
                        text: 'Guasrdar',
                        iconCls: 'x-icon-save',
                        handler: function(a, b, c) {
                            formSlide.getForm().submit({
    //                            waitMsg: 'Guardando diapositiva...',
                                success: function(form, action) {
                                    stSlides.load();
                                },
                                failure: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Error en la operaci\u00F3n',
                                        msg: _getErrorFromArray(res.errors),
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR,
                                        minWidth: 300
                                    });
                                }
                            });
                        }
                    }
                ]
            });
            
            var htmlJPlayer = '<div id="jplayer" class="jp-jplayer"></div>';
            htmlJPlayer = htmlJPlayer + '<div id="jp_container_1" style="width:100%;" class="jp-audio">'+ jQuery("#jplayer_template").html() +'</div>';

            var ppt = Ext.create('Ext.panel.Panel', {
                height: 587,
                layout: 'border',
                visible:false,
                id: 'selPanel',
                items: [
                    {
                        title: 'Diapositivas',
                        region: 'west',
                        split: true,
                        margins: '5 5 5 5',
                        width: 180,
                        items: [
                            {
                                xtype: 'button',
                                margin: '20',
                                text: 'Nueva',
                                iconCls: 'x-icon-add',
                                handler: function(a, b, c) {
                                    if(object && object.presentation){
                                        Ext.getCmp('imgslide').setSrc("");
                                        formSlide.getForm().reset();
                                        formSlide.getForm().url = BASE_URL+"slides/add";
                                        formSlide.getForm().findField("elem_presentations_id").setValue(object.presentation.id);
                                        
                                        $("#jplayer").jPlayer("stop");
                                        $("#jplayer").jPlayer("setMedia", {
                                            mp3: ""
                                        });
                                        $(".jp-title ul li").text("");
                                        
                                        formSlide.enable();
                                    }
                                    else{
                                        alert("Debe definir [Detalle Presentación] en el formulario superior antes de crear una diapositiva.");
                                    }
                                }
                            },
                            {
                                xtype: 'button',
                                margin:'0 0 0 10',
                                iconCls: 'x-icon-ppt-go',
                                handler: function(a, b, c) {

                                }
                            },
                            {
                                id: 'gSlides',
                                xtype: 'grid',
                                layout: 'fit',
                                scroll: true,
                                width: '100%',
                                height: 400,
                                autoScroll: true,
                                autoSizeColumns: true,
                                frame: false,
                                selModel: new Ext.selection.RowModel({singleSelect: true}),
                                loadMask: true,
                                store: stSlides,
                                columns: [
                                    {header: 'ID', hidden: true, align: 'center', dataIndex: 'id'},
                                    {
                                        header: 'Diapositiva',
                                        flex: 0.08, align: 'left', dataIndex: 'imgpath',
                                        renderer: function(value, m, record) {
                                            var img = '<img class="elem_ppt_slide_img" src="' + record.get('imgpath') + '" title="' + record.get('title') + '"/>';
                                            return img;
                                        }
                                    },
                                    {header: 'Titulo', flex: 0.15, dataIndex: 'title'}
                                ],
                                listeners: {
                                    cellclick: function(g, td, cellIndex, record, tr, rowIndex, e, eOpts) {
                                        formSlide.getForm().url = BASE_URL+"slides/edit";
                                    
    //                                    formSlide.getForm().findField("elem_presentations_id").setValue(record.get('elem_presentations_id'));
                                        Ext.getCmp('imgslide').setSrc(record.get('imgpath'));
                                        
                                        $("#jplayer").jPlayer("setMedia", {
                                            mp3: record.get('audiopath')
                                        });
                                        $("#jplayer").jPlayer("play");
                                        
                                        var audio = record.get('audiopath').split("/");
                                        $(".jp-title ul li").text(audio[audio.length-1]);
                                        
                                        formSlide.getForm().findField("imgpath").setValue(record.get('imgpath'));
                                        formSlide.getForm().findField("audiopath").setValue(record.get('audiopath'));
                                        formSlide.getForm().findField("title").setValue(record.get('title'));
                                        formSlide.getForm().findField("description").setValue(record.get('description'));
                                        formSlide.getForm().findField("index").setValue(record.get('index'));
                                        formSlide.getForm().findField("effect").setValue(record.get('effect'));
                                        formSlide.getForm().findField("id").setValue(record.get('id'));
                                        formSlide.enable();

                                    }
                                }
                            }
                        ]
                    },
                    {
                        title: 'Detalle',
                        collapsible: false,
                        split: true,
                        margins: '5 10 5 0',
                        region: 'center',
                        layout: 'hbox',
                        items: [
                            {
                                xtype: 'container',
                                layout: {
                                    type: 'vbox',
                                    align: 'stretch',
                                    pack: 'start',
                                },
                                flex: .4,
                                items: [
                                    {
                                        xtype: 'button',
                                        width: 20,
                                        height: 30,
                                        iconCls: 'x-icon-image-edit',
                                        text: 'Cambiar Imagen',
                                        handler: function() {
                                            var finderx = new CKFinder();
                                            finderx.selectActionFunction = function(url, data) {
                                                Ext.getCmp('imgslide').setSrc(url);
                                                formSlide.getForm().findField("imgpath").setValue(url);
                                            };
                                            finderx.popup();
                                        }
                                    },
                                    {
                                        xtype: 'image',
                                        flex: 2,
                                        height: 400,
                                        id: 'imgslide'
                                    },
                                        {
                                        xtype: 'button',
                                        width: 20,
                                        height: 30,
                                        iconCls: 'x-icon-audio-edit',
                                        text: 'Cambiar Audio',
                                        handler: function() {
                                            var finderx = new CKFinder();
                                            finderx.selectActionFunction = function(url, data) {
                                                $("#jplayer").jPlayer("setMedia", {
                                                    mp3: url
                                                });
                                                $("#jplayer").jPlayer("play");
                                                
                                                formSlide.getForm().findField("audiopath").setValue(url);
                                                
                                                url = url.split("/");
                                                $(".jp-title ul li").text(url[url.length-1]);
                                            };
                                            finderx.popup();
                                        }
                                    },
                                    {
                                        xtype: 'panel',
                                        height:200,
                                        html: htmlJPlayer
                                    }
                                ]
                            },
                            formSlide
                        ]
                    }
                ]
            });
            var formPPT = Ext.create('Ext.form.Panel', {
                collapsible:true,
                collapsed:true,
                title:'Detalle Presentación',
                border: 0,
                url: BASE_URL + 'presentations/add',
                items: [
                    {
                        xtype: 'hidden',
                        margin: '0 0 0 30',
                        name: 'type_objects_id'
                    },
                    {
                        xtype: 'hidden',
                        margin: '0 0 0 30',
                        name: 'objects_id'
                    },
                    {
                        xtype: 'hidden',
                        name: 'id'
                    },
                    {
                        xtype: 'textfield',
                        margin: '0 0 0 30',
                        name: 'name',
                        fieldLabel: 'Título'
                    },
                    {
                        xtype: 'textarea',
                        margin: '0 0 0 30',
                        name: 'description',
                        fieldLabel: 'Descripción'
                    },
                    {
                        xtype:'button',
                        margin: '0 0 10 105',
                        text:'Guardar Cambios',
                        iconCls: 'x-icon-save',
                        handler: function(a, b, c) {
                            formPPT.getForm().submit({
                                success: function(form, action) {
                                    var obj = Ext.decode(action.response.responseText).object;
                                    var res = Ext.decode(action.response.responseText);
                                    updateObjectReferences(res.data.object);
                                    /*
                                    ppt.setVisible(true);
                                    formPPT.getForm().url = BASE_URL+"presentations/edit";
                                    object.presentation = {};
                                    object.presentation.id = obj.id;
                                    object.presentation.type_objects_id = obj.type_objects_id;

                                    formPPT.getForm().findField("type_objects_id").setValue(obj.type_objects_id);
                                    formPPT.getForm().findField("id").setValue(obj.id);*/
                                },
                                failure: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Error en la operaci\u00F3n',
                                        msg: _getErrorFromArray(res.errors),
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR,
                                        minWidth: 300
                                    });
                                }
                            });
                        }
                    }
                ]
            });
            function updateObjectReferences(newObject){
                object = newObject;
                //si el objeto tema existe
                if(object && object.name){
                    if(Ext.getCmp('tabPPT')) Ext.getCmp('tabPPT').setDisabled(false);
                    if(Ext.getCmp('tabTEST')) Ext.getCmp('tabTEST').setDisabled(false);
                    if(Ext.getCmp('tabFILES')) Ext.getCmp('tabFILES').setDisabled(false);



                    formObject.getForm().url = BASE_URL+"objects/edit";
                    formObject.getForm().findField("id").setValue(object.id);
                    formObject.getForm().findField("type_objects_id").setValue(object.type_objects_id);
                    formObject.getForm().findField("name").setValue(object.name);
                    formObject.getForm().findField("description").setValue(object.description);
                    formObject.getForm().findField("ucreated").setValue(object.ucreated);
                    formObject.getForm().findField("dcreated").setValue(object.dcreated);
                    formObject.getForm().findField("umodified").setValue(object.umodified);
                    formObject.getForm().findField("dmodified").setValue(object.dmodified);
                    formObject.getForm().findField("category_id").setValue(object.category_id);
                    formObject.getForm().findField("version").setValue(object.version);
                    formObject.getForm().findField("status").setValue(object.status);

                    formObject.getForm().findField("status").setReadOnly(false);

                    Ext.getCmp("featuredImageObject").setSrc(object.featuredImage);
                    
                    //configuramos objects_id en ppt
                    formPPT.getForm().findField("objects_id").setValue(object.id);
                    formPPT.getForm().findField("type_objects_id").setValue(5);
                    //configuramos el objeto como prueba
                    formTest.getForm().findField("type_objects_id").setValue(6);
                    //configuramos objects_id en prueba
                    formTest.getForm().findField("objects_id").setValue(object.id);
                    //asociamos el formulario de recursos y archivos al obnjeto tema
                    if(formResource)
                        formResource.getForm().findField("parent").setValue(object.id);

                    stResourceFiles.getProxy().extraParams = {parent: object.id};
                    stResourceFiles.load();
                }
                //si el objeto tema posee presentacion
                if(object.presentation && object.presentation.name){
                    formPPT.getForm().url = BASE_URL+"presentations/edit";
                    formPPT.getForm().findField("type_objects_id").setValue(object.presentation.type_objects_id);
                    formPPT.getForm().findField("id").setValue(object.presentation.id);
                    formPPT.getForm().findField("name").setValue(object.presentation.name);
                    formPPT.getForm().findField("description").setValue(object.presentation.description);

                    formSlide.getForm().findField("elem_presentations_id").setValue(object.presentation.id);
                    
                    formPPT.collapse();
                    ppt.setVisible(true);


                    stSlides.getProxy().extraParams = {elem_presentations_id: object.presentation.id};
                    stSlides.load();
                }
                else{
                    //formPPT.expand();
                    //ppt.setVisible(false);
                }
                //si el objeto tema posee prueba
                if(object.test && object.test.title){
                    formTest.getForm().url = BASE_URL+"test/edit";
                    formTest.getForm().findField("type_objects_id").setValue(object.test.type_objects_id);
                    formTest.getForm().findField("id").setValue(object.test.id);
                    formTest.getForm().findField("title").setValue(object.test.title);
                    formTest.getForm().findField("description").setValue(object.test.description);

                    stQuestions.getProxy().extraParams = {elem_test_id: object.test.id};

                }
            }
            formObject = Ext.create('Ext.form.Panel', {
                bodyPadding: 40,
                height:650,
                border:0,
                width:'100%',
                url: BASE_URL + 'objects/add',
                layout:'hbox',
                fieldDefaults: {
                    labelAlign: 'left',
                    labelWidth: 120,
                    anchor: '30%'
                },
                items: [
                    {
                        xtype:'container',
                        flex:1,
                        items:[
                            {
                                xtype: 'image',
                                height: 200,
                                width:200,
                                id: 'featuredImageObject'
                            }
                        ]
                    },
                    {
                        xtype:'container',
                        layout:'vbox',
                        flex:2,
                        items:[
                            {
                                xtype: 'hidden',
                                name: 'featuredImage'
                            },
                            {
                                xtype: 'hidden',
                                name: 'type_objects_id',
                                value:CFG.type_object_theme
                            },
                            {
                                xtype: 'hidden',
                                name: 'id'
                            },
                            {
                                xtype: 'textfield',
                                name: 'name',
                                fieldLabel: 'Nombre Tema'
                            },
                            {
                                xtype: 'textarea',
                                name: 'description',
                                fieldLabel: 'Descripción Tema'
                            },
                            {
                                xtype: 'combo',
                                store: stCategories,
                                editable: false,
                                displayField: 'name',
                                name: 'category_id',
                                valueField: 'id',
                                fieldLabel: 'Categoría',
                                queryMode: 'local'
                            },
                            {
                                xtype: 'button',
                                //width: 20,
                                margin:'5 0 10 195',
                                iconCls: 'x-icon-image-edit',
                                text: 'Configurar Imagen',
                                handler: function() {
                                    var finderx = new CKFinder();
                                    finderx.selectActionFunction = function(url, data) {
                                        Ext.getCmp('featuredImageObject').setSrc(url);
                                        formObject.getForm().findField("featuredImage").setValue(url);
                                    };
                                    finderx.popup();
                                }
                            },
                            {
                                xtype: 'combo',
                                store: stObjectStatus,
                                editable: false,
                                readOnly:object?false:true,
                                displayField: 'name',
                                name: 'status',
                                valueField: 'id',
                                fieldLabel: 'Estado',
                                queryMode: 'local',
                                listeners:{
                                    select:function(a,b,c){
                                        if(object && object.id){
                                            b = b[0];
                                            var status = b.get('id');
                                            Ext.Ajax.request({
                                                url: BASE_URL + 'objects/changeStatus',
                                                method: 'POST',
                                                params: {id: object.id, status:status},
                                                success:function(action) {   
                                                    var res = Ext.decode(action.responseText);
                                                    if(res.success){
                                                        object.version = res.data.version;
                                                        formObject.getForm().findField("version").setValue(object.version);
                                                        Ext.MessageBox.show({
                                                            title: 'Operacion exitosa',
                                                            msg: "Objeto actualizado",
                                                            buttons: Ext.MessageBox.OK,
                                                            icon: Ext.MessageBox.SUCCESS,
                                                            minWidth:300
                                                        });
                                                    }
                                                    else{
                                                        Ext.MessageBox.show({
                                                            title: 'Error en la operaci\u00F3n',
                                                            msg: _getErrorFromArray(res.errors),
                                                            buttons: Ext.MessageBox.OK,
                                                            icon: Ext.MessageBox.ERROR,
                                                            minWidth:300
                                                        });
                                                    }
                                                },
                                                failure:function(form, action) {     
                                                    if(action.failureType == 'load'){                            
                                                        Ext.Msg.alert('Error', action.result.reason);
                                                    } 
                                                    else{
                                                        Ext.Msg.alert('Alerta!', 'Servidor no encontrado: ' + action.response.responseText); 
                                                    } 
                                                }
                                            });
                                        }
                                        
                                    }
                                }
                            },
                            {
                                xtype: 'textfield',
                                readOnly: true,
                                name:'ucreated',
                                fieldLabel: 'Creado por'
                            },
                            {
                                xtype: 'textfield',
                                name:'dcreated',
                                readOnly: true,
                                fieldLabel: 'Fecha Creación'
                            },
                            {
                                xtype: 'textfield',
                                readOnly: true,
                                name:'umodified',
                                fieldLabel: 'Modificado por'
                            },
                            {
                                xtype: 'textfield',
                                name:'dmodified',
                                readOnly:true,
                                fieldLabel: 'Fecha Modificación'
                            },
                            {
                                xtype: 'textfield',
                                name:'version',
                                readOnly:true,
                                fieldLabel: 'VERSION'
                            }
                        ]
                    }
                    
                ],
                buttons: [
                    {
                        xtype: 'button',
                        margin: '20',
                        text: 'Guardar',
                        iconCls: 'x-icon-save',
                        handler: function(a, b, c) {
                            //eliminamos esta propiedad ya que solo se modifica cuando se selecciona el combobox
                            //formObject.getForm().findField("status").setValue(res.data.dmodified);

                            formObject.getForm().submit({
                                success: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    if(!object){
                                        updateObjectReferences(res.data.object)
                                        Ext.MessageBox.show({
                                            title: 'Operación exitosa',
                                            msg: "Tema creado en forma exitosa",
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.INFO,
                                            minWidth: 300
                                        });
                                    }
                                    else{
                                        formObject.getForm().findField("dmodified").setValue(res.data.dmodified);
                                        formObject.getForm().findField("umodified").setValue(res.data.umodified);
                                    }
                                },
                                failure: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Error en la operaci\u00F3n',
                                        msg: _getErrorFromArray(res.errors),
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR,
                                        minWidth: 300
                                    });
                                }
                            });
                        }
                    }
                ]
            });
            var formTest = Ext.create('Ext.form.Panel', {
                collapsible:true,
                collapsed:true,
                title:'Detalle Prueba',
                border: 0,
                url: BASE_URL + 'test/add',
                items: [
                    {
                        xtype: 'hidden',
                        margin: '0 0 0 30',
                        name: 'type_objects_id'
                    },
                    {
                        xtype: 'hidden',
                        margin: '0 0 0 30',
                        name: 'objects_id'
                    },
                    {
                        xtype: 'hidden',
                        name: 'id'
                    },
                    {
                        xtype: 'textfield',
                        margin: '0 0 0 30',
                        name: 'title',
                        fieldLabel: 'Título'
                    },
                    {
                        xtype: 'textarea',
                        margin: '0 0 0 30',
                        name: 'description',
                        fieldLabel: 'Descripción'
                    },
                    {
                        xtype:'button',
                        margin: '0 0 10 105',
                        text:'Guardar Cambios',
                        iconCls: 'x-icon-save',
                        handler: function(a, b, c) {
                            formTest.getForm().submit({
                                success: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    updateObjectReferences(res.data.object);
                                    Ext.MessageBox.show({
                                        title: 'Operacion exitosa',
                                        msg: "Prueba creada en forma exitosa.",
                                        buttons: Ext.MessageBox.OK,
                                        minWidth: 300
                                    });
                                },
                                failure: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Error en la operaci\u00F3n',
                                        msg: _getErrorFromArray(res.errors),
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR,
                                        minWidth: 300
                                    });
                                }
                            });
                        }
                    }
                ]
            });
            grid = Ext.create('Ext.grid.Panel', {
                columnLines:true,
                remoteSort:true,
                loadMask: true,
                fit:true,
                forceFit:true,
                height: 500,
                width: '100%',
                selModel: new Ext.selection.RowModel({singleSelect: true}),
                dockedItems: [
                    {
                        xtype: 'pagingtoolbar',
                        store: stResourceFiles,
                        dock: 'bottom',
                        displayInfo: true
                    }, 
                    {
                        xtype: 'toolbar',
                        dock: 'top',
                        defaults: {
                            labelStyle: 'font-weight:bold;'
                        },
                        items: [
                            {
                                id: 'add',
                                iconCls: 'x-icon-add',
                                text: 'Nuevo Recurso',
                                handler: function() {
                                    addResource();
                                }
                            }, 
                            {
                                id: 'del',
                                tooltip: 'Eliminar Recurso',
                                iconCls: 'x-icon-delete',
                                text: 'Eliminar',
                                handler: function() {
                                    if (!grid.getSelectionModel().hasSelection()) {
                                        Ext.Msg.alert('Error', 'Primero debe seleccionar un registro.');
                                        return;
                                    }
                                    var selModel = grid.getSelectionModel().getSelection();
                                    var id = selModel[0].data.id;
                                    Ext.Msg.show({
                                        title: 'Confirme',
                                        msg: '¿Desea eliminar el recurso ' + selModel[0].data.name + '?',
                                        buttons: Ext.Msg.YESNO,
                                        fn: function(btn) {
                                            if (btn == 'yes') {
                                                Ext.Ajax.request({
                                                    url: BASE_URL + 'objects/del',
                                                    method: 'POST',
                                                    params: {id: id},
                                                    success:function(action) {   
                                                        var res = Ext.decode(action.responseText);
                                                        if(res.success){
                                                            grid.getStore().loadPage(1);  
                                                        }
                                                        else{
                                                            Ext.MessageBox.show({
                                                                title: 'Error en la operaci\u00F3n',
                                                                msg: _getErrorFromArray(res.errors),
                                                                buttons: Ext.MessageBox.OK,
                                                                icon: Ext.MessageBox.ERROR,
                                                                minWidth:300
                                                            });
                                                        }
                                                    },
                                                    failure:function(form, action) {     
                                                        if(action.failureType == 'load'){                            
                                                            Ext.Msg.alert('Error', action.result.reason);
                                                        } 
                                                        else{
                                                            Ext.Msg.alert('Alerta!', 'Servidor no encontrado: ' + action.response.responseText); 
                                                        } 
                                                    }
                                                });
                                                
                                            }
                                        }
                                    });
                                }
                            }
                        ]
                    }
                ],
                listeners: {
                    itemdblclick: function(dataview, record, item, index, e) {
                        var selModel = grid.getSelectionModel().getSelection();
                        var record = selModel[0];
                        addResource(record);    
                    }
                },
                store: stResourceFiles,
                columns: [
                    {
                        header: 'Tipo Recurso',
                        dataIndex: 'category_name'
                    },
                    {
                        header: 'Nombre',
                        dataIndex: 'name'
                    },
                    
                    {
                        header: 'Descripción',
                        dataIndex: 'description'
                    }, {
                        header: 'F. Modificación',
                        dataIndex: 'dmodified'
                    }, {
                        header: 'F. Creación',
                        dataIndex: 'dcreated'
                    }, 
                    {
                        header: 'Creado por',
                        dataIndex: 'ucreated'
                    }, 
                    {
                        header: 'Modificado por',
                        dataIndex: 'umodified'
                    },
                    {
                        xtype: 'actioncolumn',
                        header: 'Descargar',
                        align:'center',
                        width: 50,
                        items: [
                            {
                                icon: '../../../images/icons/arrow_down.png',
                                // Use a URL in the icon config
                                tooltip: 'Descargar',
                                handler: function (grid, rowIndex, colIndex) {
                                    var rec = grid.getStore().getAt(rowIndex);
                                    window.open(rec.get("content"));
                                }
                            }
                        ]
                    }
                ]
            });
    ////      formulario de seleccion multiple  
            fObjectSM = {
                id:'fObjectSM',
                xtype:'form',
                frame:false,
                border: false,
                visible:false,
                url: BASE_URL + 'questions/add',
                layout:'vbox',
                items: [
                    {
                        xtype: 'form',
                        layout: 'vbox',
                        frame:false,
                        border: false,
                        id:'ctDinamico',
                        items: [_getSMAnswerFrom(n,false,3)]
                    },
                    {
                        xtype: 'container',
                        layout: 'hbox',
                     //   id:'ctAddForms',
                        items:[
                            {
                                xtype: 'radiofield',
                                margin: '0 0 0 10'
                            },
                            {
                                xtype: 'textfield',
                                margin: '0 0 0 10',
                                name: 'description_dinamyc',
                                fieldStyle: 'color:#C7C7C7;',
                                handleMouseEvents: true,
                                readOnly:true,
                                value:'Haz clic para añadir una opción',
                                listeners:{
                                    render: function(cmp) { 
                                        this.getEl().on('mousedown', function(a,b,c){
                                            n++;//aumentamos contador de formulario dinamico
                                            Ext.getCmp('ctDinamico').add(_getSMAnswerFrom(n,false,3));
                                        }); 
                                    }
                                }
                            },
                            {
                                xtype: 'checkboxfield',
                                margin: '0 0 0 10'
                            }
                        ]
                    }
                ]
            };
            //formulario terminos pareados
            fObjectTP = {
                id:'fObjectTP',
                xtype:'form',
                frame:false,
                border: false,
                visible:false,
                url: BASE_URL + 'questions/add',
                layout:'vbox',
                items: [
                    {
                        xtype: 'form',
                        layout: 'vbox',
                        frame:false,
                        border: false,
                        id:'ctDinamicoTP',
                        items: [_getSMAnswerFrom(n,false,2)]
                    },
                    {
                        xtype: 'container',
                        layout: 'hbox',
                     //   id:'ctAddForms',
                        items:[
                            {
                                xtype: 'textfield',
                                margin: '0 0 0 10',
                                name: 'description_dinamyc',
                                fieldStyle: 'color:#C7C7C7;',
                                fieldLabel:'Nuevo',
                                handleMouseEvents: true,
                                readOnly:true,
                                value:'Haz clic para añadir una opción',
                                listeners:{
                                    render: function(cmp) { 
                                        this.getEl().on('mousedown', function(a,b,c){
                                            n++;//aumentamos contador de formulario dinamico
                                            Ext.getCmp('ctDinamicoTP').add(_getSMAnswerFrom(n,false,2));
                                        }); 
                                    }
                                }
                            },
                            {
                                xtype: 'checkboxfield',
                                margin: '0 0 0 10'
                            }
                        ]
                    }
                ]
            };

            var screen = window.screen.width*0.1;
            
            function add(question) {
                deletedAnswers = [];
                //solo si no existe lo creamos
                if(!win){
                    formQuestions = Ext.create('Ext.form.Panel', {
                        border: 0,
                        height:400,
                        autoScroll:true,
                        scroll:true,
                        margin: '20 0 30 20',
                        url: BASE_URL + 'questions/add',
                        items: [
                            {
                                xtype: 'hidden',
                                name: 'id'
                            },
                            {
                                xtype:'container',
                                layout:'hbox',
                                items:[
                                    {
                                        xtype: 'label',
                                        text: 'Enunciado Pregunta',
                                        margin: '0 0 0 0',
                                        name:'description',
                                        value: 'Enunciado Pregunta'
                                    }
                                ]
                            },

                            {
                                xtype: 'container',
                                html:'<div class="elem_question_title" id="ckeditor"></div>',
                                id: 'ckeditorContainer'
                            },
                            {
                                xtype      : 'fieldcontainer',
                                fieldLabel : 'Verdadero?',
                                id:'ctVF',
                                hidden:true,
                                defaultType: 'checkboxfield',
                                items: [
                                    {
                                        xtype: 'checkboxfield',
                                        width:200,
                                        checked:false,
                                        inputValue: false,
                                        name:'enunciadoValue'
                                    }
                                ]
                            },
                            {
                                xtype: 'combo',
                                store: stTypeQuestions,
                                editable: false,
                                readOnly:true,
                                margin: '20 0 0 0',
                                displayField: 'name',
                                name: 'type_questions_id',
                                valueField: 'id',
                                fieldLabel: 'Tipo Pregunta',
                                queryMode: 'local',
                                listeners:{
                                    change:function(a,b,c){
                                        //ocultamos todos los formularios
                                        if(Ext.getCmp('fObjectSM')){
                                            Ext.getCmp('fObjectSM').setVisible(false);
                                        }
                                        if(Ext.getCmp('fObjectTP')){
                                            Ext.getCmp('fObjectTP').setVisible(false);
                                        }
                                        if(Ext.getCmp("ctVF")){
                                            Ext.getCmp("ctVF").setVisible(false);
                                        }
                                        //mostramos el que selecciono solamente
                                        if(b == 3){
                                            if(!Ext.getCmp('fObjectSM')){
                                                Ext.getCmp("ctQuestionForm").add(fObjectSM);
                                            }
                                            Ext.getCmp('fObjectSM').setVisible(true);
                                        }
                                        else{
                                            //terminos pareados
                                            if(b == 2){
                                                if(!Ext.getCmp('fObjectTP')){
                                                    Ext.getCmp("ctQuestionForm").add(fObjectTP);
                                                }
                                                Ext.getCmp('fObjectTP').setVisible(true);
                                            }
                                            else{
                                                //verdadero falso
                                                if(b == 1){
                                                    if(formQuestions){
                                                        Ext.getCmp("ctVF").setVisible(true);
                                                    }
                                                }
                                            }
                                        }
                                        
                                        Ext.getCmp("ctQuestionForm").doLayout();
                                    }
                                }
                            },
                            
                            {
                                xtype: 'container',
                                margin: '20 0 0 0',
                                autoScroll:true,
                                scroll:true,
                                frame:false,
                                border: false,
                                id: 'ctQuestionForm'
                            }
                        ]
                    });

                    win = new Ext.Window({
                        title: 'Pregunta',
                        resizable: false,
                        width: 550,
                        height: 600,
                        forceFit: true,
                        frame: false,
                        layout: 'fit',
                        modal: false,
                        plain: true,
                        buttonAlign: 'center',
                        items: formQuestions,
                        closable: false,
                        buttons: [{
                                text: 'Guardar',
                                iconCls: 'x-icon-save',
                                handler: function() {
                                    if(object.test && object.test.id){
                                        _sendQuestion(formQuestions.getForm().url);
                                    }
                                    else{
                                        alert("Debe definir la prueba en el formulario superior antes de crear las preguntas.");
                                    }
                                }
                            }, {
                                text: 'Cerrar',
                                iconCls: 'x-icon-cancel',
                                handler: function() {
                                    win.hide();
                                }
                            }]
                    });

                    win.on('close', function() {
                        win.toggleCollapse();
                    });
                    win.on('minimize', function() {
                        win.toggleCollapse();
                    });

                }
                
                win.on("render",function(){
                    formQuestions.on("render",function(){
                        if(!_editor){
                            _editor = CKEDITOR.replace( 'ckeditor' , _editorCFG);
                            CKFinder.setupCKEditor(_editor, _editorCFG);
                            _editor.setData("");
                        }

                        resetFullForm(Ext.getCmp('ctDinamico'));
                        resetFullForm(Ext.getCmp('ctDinamicoTP'));
                         
                        formQuestions.getForm().reset();

                        if(question){
                            _editor.setData(question.description);
                            if(Ext.getCmp('ctDinamico')){
                                jQuery.each(question.answers,function(i,answer){
                                    n++;
                                    Ext.getCmp('ctDinamico').add(_getSMAnswerFrom(n,answer,3));
                                });
                            }
                            formQuestions.getForm().findField("id").setValue(question.id);
                            formQuestions.getForm().findField("type_questions_id").setValue(question.type_questions_id);
                            formQuestions.getForm().findField('type_questions_id').setReadOnly(true);

                            if(question.type_questions_id == 1){
                                formQuestions.getForm().findField("enunciadoValue").setValue(question.value?true:false);
                            }

                        }
                    });
                });

                win.show();

                //limpiando contenedor dinamico si o si
                resetFullForm(Ext.getCmp('ctDinamico'));
                resetFullForm(Ext.getCmp('ctDinamicoTP'));

                formQuestions.getForm().reset();

                n = 0;
                

                if(question){
                    formQuestions.getForm().url = BASE_URL+"questions/edit";
                    _editor.setData(question.description);
                    formQuestions.getForm().findField("id").setValue(question.id);
                    formQuestions.getForm().findField("type_questions_id").setValue(question.type_questions_id);
                    //formulario respuestas tipo SM
                    if(Ext.getCmp('ctDinamico') && question.type_questions_id == 3){
                        jQuery.each(question.answers,function(i,answer){
                            n++;
                            Ext.getCmp('ctDinamico').add(_getSMAnswerFrom(n,answer,question.type_questions_id));
                        });
                        
                    }
                    //formulario respuestas tipo TP
                    if(Ext.getCmp('ctDinamicoTP') && question.type_questions_id == 2){
                        jQuery.each(question.answers,function(i,answer){
                            n++;
                            Ext.getCmp('ctDinamicoTP').add(_getSMAnswerFrom(n,answer,question.type_questions_id));
                        });
                    }
                    //formulario VF
                    if(question.type_questions_id == 1){
                        Ext.getCmp('ctVF').setVisible(true);
                        if(question.value === "1")
                            formQuestions.getForm().findField("enunciadoValue").setValue(true);
                        else formQuestions.getForm().findField("enunciadoValue").setValue(false);
                    }
                }
                else{
                    _editor.setData("");
                    formQuestions.getForm().url = BASE_URL+"questions/add";
                    formQuestions.getForm().findField('type_questions_id').setReadOnly(false);
                }
            }
            function addResource(record) {
                var parent = 0;
                if(object && object.id) parent = object.id;
                formResource = new Ext.FormPanel({
                    anchor: '100%',
                    url: BASE_URL + 'objects/add',
                    layout: 'column',
                    frame: false,
                    bodyStyle: 'padding:5px 5px 0',
                    items: [{
                            xtype: 'container',
    //                        columnWidth: .5,
                            layout: 'anchor',
                            items: [
                                {
                                    xtype:'hidden',
                                    name:'id'
                                },
                                {
                                    xtype:'hidden',
                                    name:'type_objects_id',
                                    value:CFG.type_object_file
                                },
                                {
                                    xtype:'hidden',
                                    name:'parent',
                                    value:parent
                                },
                                {
                                    xtype: 'combo',
                                    store: stCategorieResources,
                                    editable: false,
                                    displayField: 'name',
                                    name: 'category_id',
                                    valueField: 'id',
                                    fieldLabel: 'Tipo Recurso',
                                    queryMode: 'local'
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: 'Nombre',
                                    name: 'name',
                                    anchor:'96%'
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: 'Descripción',
                                    name: 'description',
                                    anchor:'96%'
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: 'Archivo',
                                    readOnly:true,
                                    name:'fileTitle',
                                    anchor:'96%'
                                },
                                {
                                    xtype:'hidden',
                                    name:'content'
                                },
                                {
                                    xtype: 'button',
                                    width: 200,
                                    //height: 30,
                                    margin:'0 0 0 105',
                                    iconCls: 'x-icon-folder_explorer',
                                    text: 'Buscar Archivo',
                                    handler:function(){
                                        var finderx = new CKFinder();
                                        finderx.selectActionFunction = function(url, data) {
                                            formResource.getForm().findField("content").setValue(url);
                                            var url2 = url.split("/");
                                            formResource.getForm().findField("fileTitle").setValue(url2[url2.length-1]);
                                        };
                                        finderx.popup();
                                    }
                                }
                            ]
                        }]
                });

                var winRes = new Ext.Window({
                    title: 'Crear Recurso',
                    resizable: false,
                    width: 400,
                    height: 350,
                    forceFit: true,
                    frame: false,
                    layout: 'fit',
                    modal: true,
                    plain: true,
                    buttonAlign: 'center',
                    items: formResource,
                    closable: true,
                    buttons: [{
                            text: 'Guardar',
                            iconCls: 'x-icon-save',
                            handler: function() {
                                if(object && object.id){
                                    formResource.getForm().submit({
                                        waitMsg: 'Enviando datos...',
                                        success: function(form, action) {
                                            stResourceFiles.load();
                                            winRes.hide();
                                        },
                                        failure: function(form, action) {
                                            var res = Ext.decode(action.response.responseText);
                                            Ext.MessageBox.show({
                                                title: 'Error en la operaci\u00F3n',
                                                msg: _getErrorFromArray(res.errors),
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox.ERROR,
                                                minWidth: 300
                                            });
                                        }
                                    });
                                }
                                else{
                                    alert("Debe definir el Tema antes de crear Recursos y archivos asociados.");
                                }
                                
                            }
                        }, {
                            text: 'Cancelar',
                            iconCls: 'x-icon-cancel',
                            handler: function() {
                                winRes.hide();
                            }
                        }]
                });
                winRes.on('minimize', function() {
                    win.toggleCollapse();
                });
                formResource.getForm().reset();
                winRes.show();
                
                if(record){
                    formResource.getForm().load({               
                        url: BASE_URL + 'objects/get',
                        params:{                        
                            id:record.get('id')
                        },
                        success:function(form, action) {                                    
                            form.url = BASE_URL + 'objects/edit';           
                            var obj = Ext.decode(action.response.responseText);
                            console.log(obj);
                            var url2 = obj.data.content.split("/");
                            formResource.getForm().findField("fileTitle").setValue(url2[url2.length-1]);
                        },
                        failure:function(form, action) {                        
                            if(action.failureType == 'load'){                            
                                Ext.Msg.alert('Error', action.result.reason);
                            } 
                            else{
                                Ext.Msg.alert('Alerta!', 'Servidor no encontrado: ' + action.response.responseText); 
                            } 
                            win.hide();
                        }
                    });
                }
            }
            
            function main(){
                if(object){
                    updateObjectReferences(object);
                }
                else{
                    disableTabs = true;
                }
                Ext.create('Ext.tab.Panel', {
                    width: '100%',
                    renderTo: 'tab-panel',
                    items: [
                        {
                            title: 'Datos Generales',
                            //height:550,
                            items: formObject
                        },
                        {
                            title: 'Presentación',
                            id:'tabPPT',
                            disabled:disableTabs,
                            items: [
                                formPPT,
                                ppt
                            ]
                        },
                        {
                            title: 'Prueba',
                            id:'tabTEST',
                            disabled:disableTabs,
                            items: [
                                formTest,
                                {
                                    xtype:'form',
                                    collapsible:true,
                                    id:'ctAllquestions',
                                    title:'Panel de Preguntas',
                                    bodyPadding:20,
                                    height:700,
                                    autoScroll:true,
                                    scroll:true,
                                    items:[
                                        {
                                            xtype:'button',
                                            margin: '0 0 10 105',
                                            text:'Nueva Pregunta XXX',
                                            iconCls: 'x-icon-add',
                                            handler: function(a, b, c) {
                                                add();
                                            }
                                        },
                                        {
                                            xtype: 'container',
                                            html:'<ol class="test_questions" id="divCreatedQuestions" style="margin-left:'+screen+'px;"></ol>',
                                            id: 'ctCreatedQuestions'
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            title: 'Archivos y/o Recursos',
                            id:'tabFILES',
                            disabled:disableTabs,
                            items:[
                                grid
                            ]
                        }
                    ]
                });

                ppt.on('render',function(){
                    $("#jplayer").jPlayer({
                        swfPath: "/js",
                        supplied: "mp3, oga"
                    });
                });
                //al cargar container de preguntas se cargan las preguntas ohhhhhh
                Ext.getCmp('ctCreatedQuestions').on("render",function(){
                    stQuestions.load();
                });
            }

            main();
        }   
        
    });
</script>

<input id="hd_context" type="hidden" value="<?php echo $breadcumb; ?>"/>
<ul class='ul_page' style="margin:0px;/*background-color: #237FCB;*/">
    <li id="tab-panel"></li>
</ul>
<!-- template usado por vista extjs -->
<div id="jplayer_template" style="display: none;">
        <div class="jp-type-single" style="width:100%;">
                <div class="jp-gui jp-interface">
                        
                        <ul class="jp-controls" style="list-style: none; list-style-type: none;">
                                <li style="display: inline;width:30px;float:left;"><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
                                <li style="display: inline;width:30px;float:left;"><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
                                <li style="display: inline;width:30px;float:left;"><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
                                <li style="display: inline;width:30px;float:left; margin-left: 15px;"><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
                                <li style="display: inline;width:30px;float:left;margin-left: 15px;"><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
                                <!--<li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>-->
                        </ul>
                        <div class="jp-title">
                            <ul>
                                    <li></li>
                            </ul>
                        </div>
                        <div class="jp-progress">
                                <div class="jp-seek-bar">
                                        <div class="jp-play-bar"></div>
                                </div>
                        </div>
                        <div class="jp-volume-bar">
                                <div class="jp-volume-bar-value"></div>
                        </div>
                        <div class="jp-time-holder">
                                <div class="jp-current-time"></div>
                                <div class="jp-duration"></div>

                                <ul class="jp-toggles">
                                        <li><a href="javascript:;" class="jp-repeat" tabindex="1" title="repeat">repeat</a></li>
                                        <li><a href="javascript:;" class="jp-repeat-off" tabindex="1" title="repeat off">repeat off</a></li>
                                </ul>
                        </div>
                </div>
        </div>
</div>

